//
//  RequestMessage.m
//  CityYouTian
//
//  Created by Avon Xu on 16/1/29.
//  Copyright © 2016年 Avon Xu. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager
#pragma mark ----->.net
+(void)asyncServiceUrl:(NSString*)URL methodName:(NSString*)methodName soapMessageDict:(NSDictionary*)soapMsgDict withBlock:(resultObjectBlock)block {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    URL =[URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self setHttpHeadManager:manager Url:URL soapDic:soapMsgDict nameSpace:WebServiceNameSpace methodName:methodName];
    
    [manager POST:URL parameters:soapMsgDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 把返回的二进制数据转为字符串
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        // 利用正则表达式取出<return></return>之间的字符串
        NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:[NSString stringWithFormat:@"(?<=%@Result\\>).*(?=</%@Result)",methodName,methodName] options:NSRegularExpressionCaseInsensitive error:nil];
        for (NSTextCheckingResult *checkingResult in [regular matchesInString:result options:0 range:NSMakeRange(0, result.length)]) {
            NSString *str = [result substringWithRange:checkingResult.range];
            id data = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            block(data, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求错误:%@",error);
        block(nil, error);
    }];
}

// 设置请求头
+(void)setHttpHeadManager:(AFHTTPSessionManager *)manager Url:(NSString*)wsUrl soapDic:(NSDictionary *)dic nameSpace:(NSString*)space methodName:(NSString*)methodname {
    
    NSString *soapStr = [SoapRequest dictionaryToDefaultSoapMessage:dic methodName:methodname];
    
    NSURL *url=[NSURL URLWithString:wsUrl];
    manager.requestSerializer.timeoutInterval = 60.0;

    [manager.requestSerializer setValue:[url host] forHTTPHeaderField:@"Host"];
    
    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%zd", soapStr.length] forHTTPHeaderField:@"Content-Length"];
    
    NSString *soapAction=[NSString stringWithFormat:@"%@%@",space,methodname];
    
    [manager.requestSerializer setValue:soapAction forHTTPHeaderField:@"SOAPAction"];
    
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {//让用户可以通过block自己组装请求参数
        return soapStr;
    }];
}


#pragma mark ---->PHP
//POST请求
+(void)postRequestURL:(NSString*)URL parameter:(id)paramts withBlock:(resultObjectBlock)block {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20.0;   //请求超时
    manager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy; //缓存策略
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];//支持类型
    manager.securityPolicy.allowInvalidCertificates = YES;  //是否允许访问证书过期的地址
    //UTF8进行编码
    URL =[URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager POST:URL parameters:paramts progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        block(responseObject, nil);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        block(nil, error);
    }];
}

//GET请求
+(void)getRequestURL:(NSString*)URL parameter:(id)paramts withBlock:(resultObjectBlock)block {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20.0;   //请求超时
    manager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy; //缓存策略
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];//支持类型
    manager.securityPolicy.allowInvalidCertificates = YES;  //是否允许访问证书过期的地址
    //UTF8进行编码
    URL =[URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:URL parameters:paramts progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        block(responseObject, nil);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        block(nil, error);
    }];
}

+ (void)postWithURL:(NSString *)url parameter:(id)paramts formDataArray:(NSArray *)formDataArray withBlock:(resultObjectBlock)block {
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paramts constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (UploadDataModel *model in formDataArray) {
            [formData appendPartWithFileData:model.data name:model.name fileName:model.filename mimeType:model.mimeType];
        }
    } error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"上传进度 ==%lf",uploadProgress.fractionCompleted);
        });
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            block(nil, error);
        } else {
            block(responseObject, nil);
        }
    }];
    [uploadTask resume];
}

+(NSString *)dateString:(NSDate *)date {
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"MMddHHmmss"];/* */    //设定时间格式,这里可以设置成自己需要的格式
    NSString *dateString = [dateFormat stringFromDate:date];
    return dateString;
}
+ (void)uploadImageWithURL:(NSString *)url parameter:(id)paramts key:(NSString*)imageKey formImage:(UIImage *)image withBlock:(resultObjectBlock)block {
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:paramts constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSString *dateString =[RequestManager dateString:[NSDate date]];
        [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:imageKey fileName:[NSString stringWithFormat:@"%@.jpg",dateString] mimeType:@"image/jpeg"];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"上传进度 ==%lf",uploadProgress.fractionCompleted);
        });
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            block(nil, error);
        } else {
            block(responseObject, nil);
        }
    }];
    [uploadTask resume];
}

@end


@implementation UploadDataModel

@end
